package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.beancontext.BeanContext;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void addAddressBook(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        addressBookMapper.addAddressBook(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.list(userId);
        return list;
    }

    @Override
    public AddressBook defaultAddreddBook() {
        Long userId = BaseContext.getCurrentId();
        return addressBookMapper.defaultAddressBook(userId);
    }

    @Override
    public AddressBook getAddressBookById(Integer id) {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.getAddressBookById(userId,id);
        return addressBook;
    }

    @Override
    public void update(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBookMapper.update(addressBook);
    }

    @Override
    public void deleteAddressBood(Integer id) {
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.deleteAddressBook(userId,id);
    }

    @Override
    public void updateDefault(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.list(userId);
        for (AddressBook book : list) {
            if(book.getIsDefault()==1){
                book.setIsDefault(0);
                book.setUserId(userId);
                addressBookMapper.update(book);
            }
        }
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }


}
